'use strict';
const path = require('path');
const fs = require('fs')
const defaultSettings = require('./src/settings.js');

// const bodyParser = require('body-parser')

let BASE_URL = '/dev-api';
const bodyParser = require("body-parser")

function resolve(dir) {
  return path.join(__dirname, dir)
}

const name = defaultSettings.title || 'vue Element Admin'; // page title

// If your port is set to 80,
// use administrator privileges to execute the command line.
// For example, Mac: sudo npm run
// You can change the port by the following method:
// port = 8080 npm run dev OR npm run dev --port = 8080
const port = process.env.port || process.env.npm_config_port || 8080; // dev port

// All configuration item explanations can be find in https://cli.vuejs.org/config/
module.exports = {
  /**
   * You will need to set publicPath if you plan to deploy your site under a sub path,
   * for example GitHub Pages. If you plan to deploy your site to https://foo.github.io/bar/,
   * then publicPath should be set to "/bar/".
   * In most cases please use '/' !!!
   * Detail: https://cli.vuejs.org/config/#publicpath
   */
  publicPath: '/',
  outputDir: 'dist',
  assetsDir: 'static',
  lintOnSave: process.env.NODE_ENV === 'development',
  productionSourceMap: false,
  devServer: {
    port: port,
    open: true,
    overlay: {
      warnings: false,
      errors: true
    },
    // proxy: {
    //   '/api': {
    //     target: "http://localhost:8080/",
    //     pathRewrite: {"^/api": ""},//打包之后去掉/api
    //     changeOrigin: true,
    //   },
    // },
    before(app) {
      app.use(bodyParser.urlencoded({extended: false}))
      app.use(bodyParser.json())
      app.get(BASE_URL + '/users/info', (req, res) => {
        res.send({
          "router_id": ['permission1', 'permission1/admin', 'permission2', 'permission2/viewer', 'editorBtn'],
          "roles": ["admin"],
          "introduction": "I am a super administrator",
          "avatar": "https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif",
          "name": "Super Admin"
        })
      })
      app.post("/users/login", (req, res) => {
          console.log(req.body)
          app.get('/getTMS', (req, res) => {
            res.send({
              code: 1,
              msg: '123'
            })
            app.get("/postTest", (req, res) => {
              res.send({code: 1, msg: "成功"})
            });
            // app.get(BASE_URL + '/users/info', (req, res) => {
            //   res.send({
            //     "router_id": ['permission1', 'permission1/admin', 'permission2', 'permission2/viewer', 'editorBtn'],
            //     "roles": ["admin"],
            //     "introduction": "I am a super administrator",
            //     "avatar": "https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif",
            //     "name": "Super Admin"

            //   })
            // });
            app.post('/postTest', (res, req) => {
              console.log('serve', req.body);
              res.send({status: 1, msg: "aa"})
              // let obj = req.body
              // console.log(obj);
              // res.send({
              //   "status":"200",
              //   "msg":'ok~~'
              // })
            })
          })
          app.get("/getTest", (req, res) => {
            res.send("ok")
          });
          app.post("/postTest", (req, res) => {
            console.log(req.body)
            res.send({
              status: 1,
              msg: "成功连接"
            })

            // app.get(BASE_URL + '/users/info', (req, res) => {
            //   res.send({
            //     "router_id": ['permission1', 'permission1/admin', 'permission2', 'permission2/viewer', 'editorBtn'],
            //     "roles": ["admin"],
            //     "introduction": "I am a super administrator",
            //     "avatar": "https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif",
            //     "name": "Super Admin"
            //
            //   })
            // });
            //获取一级分类列表
            // app.get('/getType', (req, res) => {
            //   let data = JSON.parse(fs.readFileSync(path.join(__dirname, './dataBase/type.json'), 'utf-8'))
            //   console.log(data)
            //   res.send({code: 200, res: data})
            // });
            // //获取二级分类列表
            // app.post('/getNextType', (req, res) => {
            //   let {id} = req.body
            //   let data = JSON.parse(fs.readFileSync(path.join(__dirname, './dataBase/type.json'), 'utf-8'))
            //   let arr = data.filter(item => item.id === id)
            //   res.send({
            //     code: 200,
            //     data: arr[0].nextLevel
            //   })
            // })
            //获取三级分类列表
            app.post('/getLastType', (req, res) => {
              let {id, aid} = req.body
              console.log(id, aid);
              let Data = JSON.parse(fs.readFileSync(path.join(__dirname, './dataBase/type.json'), 'utf-8'))
              let arr = Data.filter(item => item.id === id)[0].nextLevel.Area.filter(item => item.aid === aid)[0].nextLevel
              res.send({
                code: 200,
                data: arr
              })
              let data = [
                {
                  id: "000112",
                  name: "小刘",
                  Phonenumber: "18507833093",
                  password: "334455",
                  record: 15,
                  time: "2020.03.01 15:30",
                  switch: true,
                  situation: 0
                },
                {
                  id: "000113",
                  name: "小赵",
                  Phonenumber: "17332004587",
                  password: "223344",
                  record: 12,
                  time: "2020.03.01 12:30",
                  switch: false,
                  situation: 0
                },
                {
                  id: "000114",
                  name: "小胡",
                  Phonenumber: "15235004782",
                  password: "112233",
                  record: 10,
                  time: "2020.03.01 10:30",
                  switch: true,
                  situation: 0
                }
              ];
              app.post("/addlist", function (req, res) {

              })
              app.get('/list', function (req, res) {
                res.json(data);
              });
            })
            // proxy: {
            //   '/api': {
            //     target: "http://127.0.0.1:8080",//代理的地址
            //     pathRewrite: {"^/api": ""},//打包之后去掉/api
            //     changeOrigin: true,
            //   }
            // },
            // before(app) {
            //   app.use(bodyParser.urlencoded({extended:false}))
            //   app.use(bodyParser.json)
            //   app.get(BASE_URL + '/users/info', (req, res) => {
            //     res.send({
            //       "router_id": ['permission1', 'permission1/admin', 'permission2', 'permission2/viewer', 'editorBtn'],
            //       "roles": ["admin"],
            //       "introduction": "I am a super administrator",
            //       "avatar": "https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif",
            //       "name": "Super Admin"

            //     })
            //   });
            //   app.get('/shangping', function(req, res) {
            //     res.json([
            //       {
            //           bianhao:'987767',
            //           listname:'英雄联盟兰博皮肤',
            //           leixing:'皮肤',
            //           oldprice:"147.00",
            //           newprice:'100.00',
            //           num:5000,
            //           time:'2019-10-18 17:39:45',
            //           state:true,
            //           name:'英雄联盟',
            //           qufu:'北京区',
            //           type:'自营',
            //           delete:true
            //       },
            //       {
            //           bianhao:'987767',
            //           listname:'英雄联盟兰博皮肤',
            //           leixing:'皮肤',
            //           oldprice:"147.00",
            //           newprice:'100.00',
            //           num:5000,
            //           time:'2019-10-16 17:39:45',
            //           state:false,
            //           name:'英雄联盟',
            //           qufu:'北京区',
            //           type:'自营',
            //           delete:true
            //       },
            //       {
            //           bianhao:'987767',
            //           listname:'英雄联盟兰博皮肤',
            //           leixing:'皮肤',
            //           oldprice:"147.00",
            //           newprice:'100.00',
            //           num:5000,
            //           time:'2019-10-19 17:39:45',
            //           state:true,
            //           name:'英雄联盟',
            //           type:'自营',
            //           delete:false
            //       },
            //       {
            //           bianhao:'987767',
            //           listname:'英雄联盟兰博皮肤',
            //           leixing:'皮肤',
            //           oldprice:"147.00",
            //           newprice:'100.00',
            //           num:5000,
            //           time:'2019-10-18 17:39:45',
            //           state:false,
            //           name:'英雄联盟',
            //           type:'商家',
            //           delete:true
            //       },
            //       {
            //           bianhao:'987767',
            //           listname:'英雄联盟兰博皮肤',
            //           leixing:'皮肤',
            //           oldprice:"147.00",
            //           newprice:'100.00',
            //           num:5000,
            //           time:'2019-10-18 17:39:45',
            //           state:true,
            //           name:'英雄联盟',
            //           type:'商家',
            //           delete:false
            //       },
            //   ]);
            //   });
            //   app.post('/list',function(req,res){
            //     let {user,pwd}=req.body
            //     console.log(user,pwd)
            //     res.send({code:111})
            //   })
            // }
          })

        }
      )
      app.get('/getType', (req, res) => {
        let data = JSON.parse(fs.readFileSync(path.join(__dirname, './dataBase/type.json'), 'utf-8'))
        res.send({code: 200, res: data})
      });
      //获取二级分类列表
      app.post('/getNextType', (req, res) => {
        let {id} = req.body
        let data = JSON.parse(fs.readFileSync(path.join(__dirname, './dataBase/type.json'), 'utf-8'))
        let arr = data.filter(item => item.id === id)
        res.send({
          code: 200,
          data: arr[0].nextLevel
        })
      })
      //获取三级分类列表
      app.post('/getLastType', (req, res) => {
        let {id, aid} = req.body
        console.log(id, aid);
        let Data = JSON.parse(fs.readFileSync(path.join(__dirname, './dataBase/type.json'), 'utf-8'))
        let arr = Data.filter(item => item.id === id)[0].nextLevel.Area.filter(item => item.aid === aid)[0].nextLevel
        res.send({
          code: 200,
          data: arr
        })
      })
    }
  },
  configureWebpack: {
    // provide the app's title in webpack's name field, so that
    // it can be accessed in index.html to inject the correct title.
    name: name,
    resolve: {
      alias: {
        '@': resolve('src')
      }
    }
  },
  chainWebpack(config) {
    config.plugins.delete('preload') // TODO: need test
    config.plugins.delete('prefetch') // TODO: need test

    // set svg-sprite-loader
    config.module
      .rule('svg')
      .exclude.add(resolve('src/icons'))
      .end()
    config.module
      .rule('icons')
      .test(/\.svg$/)
      .include.add(resolve('src/icons'))
      .end()
      .use('svg-sprite-loader')
      .loader('svg-sprite-loader')
      .options({
        symbolId: 'icon-[name]'
      })
      .end()

    // set preserveWhitespace
    config.module
      .rule('vue')
      .use('vue-loader')
      .loader('vue-loader')
      .tap(options => {
        options.compilerOptions.preserveWhitespace = true
        return options
      })
      .end()

    config
      .when(process.env.NODE_ENV !== 'development',
        config => {
          config
            .plugin('ScriptExtHtmlWebpackPlugin')
            .after('html')
            .use('script-ext-html-webpack-plugin', [{
              // `runtime` must same as runtimeChunk name. default is `runtime`
              inline: /runtime\..*\.js$/
            }])
            .end()
          config
            .optimization.splitChunks({
              chunks: 'all',
              cacheGroups: {
                libs: {
                  name: 'chunk-libs',
                  test: /[\\/]node_modules[\\/]/,
                  priority: 10,
                  chunks: 'initial' // only package third parties that are initially dependent
                },
                elementUI: {
                  name: 'chunk-elementUI', // split elementUI into a single package
                  priority: 20, // the weight needs to be larger than libs and app or it will be packaged into libs or app
                  test: /[\\/]node_modules[\\/]_?element-ui(.*)/ // in order to adapt to cnpm
                },
                commons: {
                  name: 'chunk-commons',
                  test: resolve('src/components'), // can customize your rules
                  minChunks: 3, //  minimum common number
                  priority: 5,
                  reuseExistingChunk: true
                }
              }
            })
          config.optimization.runtimeChunk('single')
        }
      )
  }
}